﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using DevExpress.Accessibility;
using DevExpress.LookAndFeel;
using DevExpress.Utils;
using DevExpress.Utils.Design;
using DevExpress.Skins;
using DevExpress.Utils.Drawing;
using DevExpress.XtraEditors.Calendar;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.ListControls;
using DevExpress.Data;
using DevExpress.Data.Filtering;
using DevExpress.Data.Helpers;
using DevExpress.XtraEditors;

using Fcdbas.Platform.Properties;
using Fcdbas.Core;
using Fcdbas.WinUI.Forms;

namespace Fcdbas.WinUI.Controls
{
   
   
    [Description("表示 Fcdbase 下拉控件，可以同时显示其他字段的内容的下接")]
    [ToolboxBitmap(typeof(ComboBoxEdit))]
    [ToolboxItemFilter("System.Windows.Forms")]
    [DefaultBindingProperty("Text")]
    public class cLookupEdit : LookUpEdit, IReference, IOwningDataSourceBinding, IReadOnly, IValidate, IControl
    {
        public  cLookupEdit() 
            :  base()
        {
            this.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(cRecSelExtComboBox_ProcessNewValue);
            
           // this.EditValueChanged += new EventHandler(cRecSelExtComboBox_EditValueChanged);
            this.CustomDisplayText += new CustomDisplayTextEventHandler(cLookupEdit_CustomDisplayText);
          //  this.EditValueChanged += new EventHandler(cRecSelExtComboBox_EditValueChanged);
            
            //this.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(cRecSelExtComboBox_Closed);
           // this.LostFocus += new EventHandler(cRecSelExtComboBox_EditValueChanged);
           // this.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(cRecSelExtComboBox_EditValueChanging);

        }

        void cLookupEdit_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            if (OwningDataSourceBinding != null && this.DataColumn != null)
            {

                Fcdbas.Core.IEntity en = OwningDataSourceBinding.Current as Fcdbas.Core.IEntity;
                if (en != null)
                {
                    if (en.Dirtys.ContainsKey(this.DataColumn.ColumnName))
                    {
                        //this.oldForeColor = this.ForeColor;
                        this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.EditColor;
                    }
                    else
                    {
                        this.ForeColor = oldForeColor;
                    }
                }
            }
        }
        public bool IsBinding = false;
        
        public void BindValue()
        {
            //return;
            DataSourceBinding dsb = this.GetOwningDataSourceBinding();
            if (dsb == null)
                return;
            IEntity en = dsb.Current as IEntity;
            if (en == null)
                return;
            if (this.DataColumn != null && this.DataColumn.ColumnName != null)
            {
              //  this.ItemIndex = 0;
                if (en[this.DataColumn.ColumnName] != null)
                {
                    
                    this.Text = en[this.DataColumn.ColumnName].ToString();
                   
                }
                //this.EditValue = en[this.DataColumn.ColumnName];
                
            }
        }
        public void SetValueToEntity()
        {
            DataSourceBinding dsb = this.Properties.DataSource as DataSourceBinding;

            if (dsb != null && this.DataColumn != null && dsb.Session != null && dsb.Session.IsNew)
            {
                IEntity en = dsb.Current as IEntity;
                if (en != null && this.DataColumn != null && this.DataColumn.ColumnName != null)
                {
                    en[this.DataColumn.ColumnName] = this.Text;
                }
            }
        }
        private bool _isEditing;
        private Color oldForeColor = Color.Black;
        public bool IsEditing
        {
            get
            {
                return _isEditing;
            }
            set
            {
                _isEditing = value;
                //if (value)
                //{
                //    this.oldForeColor = this.ForeColor;
                //    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.EditColor;
                //}
                if (!value)
                {
                    this.ForeColor = oldForeColor;
                }
            }
        }
        
        //[Bindable(true)]
        //public new string Text
        //{
        //    get
        //    {
        //        return base.Text;
        //    }
        //    set
        //    {
        //        base.Text = value;
        //    }
        //}
        private void RefreshOtherKey(bool binding)
        {
            //return;
            BaseForm frm = this.FindForm() as BaseForm;
            if (frm == null)
                return;
           // IsBinding = true;
          
            foreach (Control control in frm.ControlList)
            {
                if (control is cLookupEdit)
                {
                    cLookupEdit rsc = control as cLookupEdit;
                  //  if (rsc.Name == this.Name)
                    //    continue;
                    if (rsc.Properties.DataSource == this.Properties.DataSource)
                    {
                        rsc.IsBinding = binding;
                       
                    }
                }
            }
           // IsBinding = false;
           
        }
        #region IReference 成员
        public bool IsDelete
        {
            set
            {
                if (value)
                {
                    Font font = new Font(this.Font, FontStyle.Strikeout);
                    this.Font = font;
                    oldForeColor = this.ForeColor;
                    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.DeleteColor;
                }
                else
                {
                    Font font = new Font(this.Font, FontStyle.Regular);
                    this.Font = font;
                    this.ForeColor = oldForeColor;
                }
            }
        }
        public bool IsReference
        {
            get
            {
                return !string.IsNullOrEmpty(Reference);
            }
        }
        public string Value
        {
            get
            {
                return this.Text;
            }
            set
            {
                this.Text = value;
            }
        }
        public string Reference
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.Reference;

                return null;
            }
        }
        private string columnName;
        public string Column
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.ColumnName;
                else
                    return columnName;
            }
            set
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    bindingItem.ColumnName = value;
                columnName = value;
            }
        }

        public Type DataType
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.DataType;

                return null;
            }
        }

        public object ReferenceValue
        {
            get
            {
                return this.Text;
            }
        }

        public void SetValue(object value)
        {
            if (value == null ||
                value is DBNull)
                return;

            this.Text = value.ToString();
        }

        #endregion
        private Color oldBackColor;
        private bool IsInput = false;
        private DataItem GetBindingItem()
        {
            return DataColumn;
           
        }
        protected override void OnGotFocus(EventArgs e)
        {
            IsInput = true;
            oldBackColor = this.BackColor;
            this.BackColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.FocusColor;
            base.OnGotFocus(e);
        }
        /// <summary>
        /// 触发获取引用字段
        /// </summary>
        private bool FireRef = false;
        protected override void OnLostFocus(EventArgs e)
        {
            IsInput = false;
            this.BackColor = oldBackColor;
            if (FireRef)
            {
                BaseForm parentForm = this.FindForm() as BaseForm;
                if (parentForm != null)
                    parentForm.FireOnTextChangedEvent(this);
                FireRef = false;
            }
            base.OnLostFocus(e);
        }
        protected override void OnEditValueChanged()
        {
            if (bindDescription != null && !string.IsNullOrEmpty(this.DescriptionColumn))
            {
                object obj = this.GetColumnValue(this.DescriptionColumn);
                if(obj != null)
                    bindDescription.Text = obj.ToString();
                bindDescription.ReadOnly = true;
            }
            if (OwningDataSourceBinding != null)
            {
                if (OwningDataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                    return;
                //if (!OwningDataSourceBinding.AllowEdit)
                //    return;
                if (!IsInput)
                    return;
                if (this.DataColumn != null && this.DataColumn.IsAssist)
                    return;
                if (!OwningDataSourceBinding.Session.IsNew && !OwningDataSourceBinding.Session.IsEdit && !OwningDataSourceBinding.Binding && !OwningDataSourceBinding.Session.RecordRefresh)
                {
                    Form frm = this.FindForm();
                    if (frm != null)
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.AM_DataSourceFieldModified, 1, OwningDataSourceBinding.Identify);
                    IsEditing = true;
                }
                Fcdbas.Core.IEntity en = OwningDataSourceBinding.Current as Fcdbas.Core.IEntity;
                if (en != null && this.DataColumn != null)
                {
                    try
                    {
                        en[this.DataColumn.ColumnName] = EditValue;
                    }
                    catch (Exception ex)
                    {
                        Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            FireRef = true;
            base.OnEditValueChanged();
        }
        private DataSourceBinding GetOwningDataSourceBinding()
        {
            if (this.DataBindings["Text"] == null && this.DataBindings["EditValue"] == null)
            {
                if (OldBinding != null)
                    return OldBinding.DataSource as DataSourceBinding;
                else
                    return null;
            }
            if (this.DataBindings["Text"]!= null )
                return this.DataBindings["Text"].DataSource as DataSourceBinding;
            if (this.DataBindings["EditValue"] != null)
                return this.DataBindings["EditValue"].DataSource as DataSourceBinding;
            else
                return null;
        }
        #region IOwningDataSourceBinding 成员
        private Binding _oldBinding;
        public Binding OldBinding
        {
            get
            {
                return _oldBinding;
            }
            set
            {
                _oldBinding = value;
            }
        }
        [Browsable(false)]
        public DataSourceBinding OwningDataSourceBinding
        {
            get { return GetOwningDataSourceBinding(); }
        }

        [Browsable(false)]
        DataSourceBinding IOwningDataSourceBinding.OwningDataSourceBinding
        {
            get { return OwningDataSourceBinding; }
        }

        [Browsable(false)]
        public DataItem BindingItem
        {
            get
            {
                return GetBindingItem();
            }
        }

        #endregion
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (readOnly)
            {
                if((Control.ModifierKeys & Keys.Control)!=Keys.Control )
                    e.Handled = true;
            }
            base.OnKeyPress(e);
        }
        protected override void OnEnter(EventArgs e)
        {
            BaseForm parentForm = this.FindForm() as BaseForm;
            if (parentForm != null)
                parentForm.FireOnEnterEvent(this);

            base.OnEnter(e);
        }
        
        private bool readOnly = true;
        #region IReadOnly 成员

        public bool ReadOnly
        {
            get
            {
                return readOnly;
            }
            set
            {
                readOnly = value;
            }
        }

        #endregion

       // private int CurrentItemIndex = 0;
        //void cRecSelExtComboBox_EditValueChanged(object sender, EventArgs e)
        //{
        //    Console.WriteLine("Current ItemIndex is : " + ItemIndex.ToString());
        //    DataSourceBinding dsb = this.Properties.DataSource as DataSourceBinding;
        //    if (dsb != null)
        //    {
               
        //        if (dsb.Session.IsNew)
        //        {
        //            IEntityList list = dsb.DataSource as IEntityList;
        //            if (list != null && this.DataColumn != null && this.DataColumn.ColumnName != null)
        //            {
        //                IEntity en = list.Find(this.DataColumn.ColumnName, this.Text);
        //                IEntity cu = dsb.Current as IEntity;
        //                if (cu != null && en != null )
        //                {
        //                    cu[this.DataColumn.ColumnName] = this.Text;
 
        //                }
                       
        //            }
                        
        //        }
        //    }
        //}

        void cRecSelExtComboBox_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            RepositoryItemLookUpEdit edit = ((LookUpEdit)sender).Properties;
            if (e.DisplayValue == null || edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;//为空或者选择项不变，不执行后续操作
            if (this.Properties.SearchMode == DevExpress.XtraEditors.Controls.SearchMode.AutoComplete)
                return;
            DataSourceBinding dsb = this.Properties.DataSource as DataSourceBinding;
            if(dsb != null)
            {
                IEntity en = dsb.Current as IEntity;
                if (en != null && this.DataColumn != null && this.DataColumn.ColumnName != null)
                {
                    en[this.DataColumn.ColumnName] = this.Text;
                }
            }
            e.Handled = true;
        }
        private cLabel bindLabel;
        public cLabel BindLabel
        {
            get
            {
                return this.bindLabel;
            }
            set
            {
                this.bindLabel = value;
            }
        }
        private cTextEdit bindDescription;
        /// <summary>
        /// 绑定显示的描述信息
        /// </summary>
        public cTextEdit BindDescription
        {
            get
            {
                return this.bindDescription;
            }
            set
            {
                this.bindDescription = value;
            }
        }
        /// <summary>
        /// 绑定描述信息的字段
        /// </summary>
        public string DescriptionColumn
        {
            get;
            set;
        }
        public string Label
        {
            get
            {
                if (bindLabel != null)
                    return bindLabel.Text;
                else
                    return "";
            }

        }
        public bool Validate()
        {
            DataSourceBinding ownerDataSourceBinding = GetOwningDataSourceBinding();
            if (DataColumn != null &&
                   DataColumn.Required &&
                   string.IsNullOrEmpty(this.Text))
            {
                WinUI.Forms.BaseForm form = this.FindForm() as WinUI.Forms.BaseForm;
                if (form != null)
                    form.ShowMessage("字段%%1不能为空！", DataColumn.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return ownerDataSourceBinding.Validate(this.DataColumn.ColumnName, this.Text);
        }
        /// <summary>
        /// 绑定的字段信息
        /// </summary>
        public DataItem DataColumn
        {
            get;
            set;
        }
    }
}
